/**
This file is part of Studentport.

   Studentport is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   Studentport is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with Studentport.  If not, see <http://www.gnu.org/licenses/>.

 **/

package com.httpclasses;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONStringer;
import org.xml.sax.SAXException;

import android.net.Uri;
import android.util.JsonReader;
import android.util.Log;

import com.groupalpha.helpers.DOMPARSER;
import com.groupalpha.helpers.Kurs;
import com.groupalpha.helpers.Tenta;

/**
 * 
 * The Class allowing the application to use and login to studentportalen. There
 * is one method for each query to studentportalen, this class must be
 * instanciated before use.
 * 
 * @author GroupAlpha
 * 
 * 
 */
@SuppressWarnings("unused")
public class perfectConnect {
	public static final int LINDHOLMEN = 0;
	public static final int CHALMERS = 1;
	public static final int LINDHOLMSPIREN = 2;
	private  Pattern wa = Pattern.compile("wa\".*?value=\"([^\"]+)\"");
	private  Pattern wresult = Pattern
			.compile("wresult\".*?value=\"([^\"]+)\"");
	private  Pattern wctx = Pattern
			.compile("wctx\".*?value=\"([^\"]+)\"");
	private  boolean hasStarted = false;
	private  Pattern viewstaten = Pattern
			.compile("__VIEWSTATE\".*?value=\"([^\"]+)\"");
	private  Pattern event = Pattern
			.compile("__EVENTVALIDATION\".*?value=\"([^\"]+)\"");
	private  String userName = "";
	private  boolean newsReady = false;
	private  String passWord = "";
	private  String[] newsString;
	private  final int timeoutConnection = 3000;
	private  final int timeoutSocket = 20000;
	private  String urlLogin = "https://idp.chalmers.se/adfs/ls/?wa=wsignin1.0&wtrealm=urn:chalmers:student&wctx=https://student.portal.chalmers.se/_layouts/Chalmers/Authenticate.aspx?Source=/sv/Sidor/default.aspx";
	private  String urlforward = "https://student.portal.chalmers.se/_trust/";
	private  String refer = "https://idp.chalmers.se/adfs/ls/?wa=wsignin1.0&wtrealm=urn%3achalmers%3astudent&wctx=https%3a%2f%2fstudent.portal.chalmers.se%2f_layouts%2fChalmers%2fAuthenticate.aspx%3fSource%3d%2fsv%2fSidor%2fdefault.aspx";
	private  List<NameValuePair> again;
	private  HttpClient client;
	private  HttpContext context;
	private  String news = "";
	private  boolean english = false;
	private  org.apache.http.client.CookieStore cookieStore;
	private static perfectConnect instance = null;
	private  boolean ready = false;

	/**
	 * empty constructor, for setting up all the instance variables
	 */
	private perfectConnect() {
		
		client = new DefaultHttpClient();
		setupClient();
	
	}
	public synchronized static perfectConnect getInstance(){
		if(instance==null)
			instance = new perfectConnect();
		return instance;
				
	}
	public  synchronized perfectConnect reInit(){
	ready=false;
	english=false;
	context=null;
	again=null;
	newsString=null;
	passWord="";newsReady=false;userName="";
	if(client!=null)
	client.getConnectionManager().shutdown();
	client=null;
	client=new DefaultHttpClient();
	setupClient();
	return getInstance();
		
	}

	/**
	 * returns the "ej avslutade kurser" page, formated to be perfect in a
	 * webview
	 * 
	 * @return the string containg the page.
	 */
	public synchronized  String getEjCourses()
			throws IllegalStateException, IOException {
		HttpGet httpget = new HttpGet(
				"https://student.portal.chalmers.se/sv/chalmersstudier/minaresultatochintyg/Sidor/EjAvslutadeKurser.aspx");
		HttpResponse hr = null;
		hr = client.execute(httpget, context);
		httpget.getParams().setBooleanParameter(
				CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
		String html = inputStreamToString(hr.getEntity().getContent());

		int start = html.indexOf("<div class=\"bm-content\"");
		int end = html
				//.indexOf("<span id=\"ctl00_ctl21_g_b0e133fe_a15d_48da_9966_ed2a7ace7e11_ctl00_lblIntroductionText2\"></span>");
				.indexOf("<a id=\"ctl00_PlaceHolderMain_ctl02_ctl00_BackLink\" href=\"https://student.portal.chalmers.se/sv/chalmersstudier/minaresultatochintyg\">Studieresultat...</a>");
		// old:
		// ctl00_ctl21_g_0a1be68d_1e10_449c_9f81_3c73e8e9a8ad_ctl00_lblIntroductionText2
		if (start != -1 && end != -1) {
			html = html.substring(start, end);

		} else
			return "error!";

		html = html.replaceAll("Högskolepoäng", "Hp")
				.replace("<table width=\"95%\">", "<table width=\"100%\">")
				.replaceAll("<p>​</p>", "");
		html = html.replaceAll("Kurshemsida saknas", "");
		html = html.replaceAll("../../../../",
				"https://studentportal.chalmers.se/");
		html = html
				.replaceAll("/sv/", "https://student.portal.chalmers.se/sv/");

		return html;
	}

	/**
	 * Same as getEjCourses but in english.
	 * 
	 * @return
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	public synchronized  String getEjCoursesEN()
			throws IllegalStateException, IOException {
		HttpGet httpget = new HttpGet(
				"https://student.portal.chalmers.se/en/chalmersstudies/courseinformation/Pages/UncompletedCourses.aspx");
		HttpResponse hr = null;
		hr = client.execute(httpget, context);
		httpget.getParams().setBooleanParameter(
				CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
		String html = inputStreamToString(hr.getEntity().getContent());

		int start = html.indexOf("<div class=\"middle\">");
		int end = html
				.indexOf("<a id=\"ctl00_PlaceHolderMain_ctl02_ctl00_BackLink\" href=\"https://student.portal.chalmers.se/en/chalmersstudies/courseinformation\">Course Information</a>");

		if (start != -1 && end != -1) {
			html = html.substring(start, end);

		} else
			return "error!";

		html = html.replaceAll("\\s+", " ")
				.replace("<table width=\"95%\">", "<table width=\"100%\">")
				.replaceAll("<p>​</p>", "");
		html = html.replaceAll("../../../../",
				"https://studentportal.chalmers.se/sv/");
		html = html
				.replaceAll("/en/", "https://student.portal.chalmers.se/en/");
		html = html.replaceAll("Hompage missing", "");

		return html;
	}

	/**
	 * 
	 * @param i
	 *            = 0 => LINDHOLMEN , 1 = CHALMERS
	 * @return
	 * @throws Exception
	 */
	public synchronized  String getBusses(int i) throws Exception {

		JSONObject obj = new JSONObject();
		JSONObject Request = new JSONObject();
		HttpClient Busclient = new DefaultHttpClient(new BasicHttpParams());
		JSONObject content = new JSONObject();
		content.put("RDC_Language", "sv-SE");
		if (i == LINDHOLMEN)
			content.put("StopAreaExternalId", "9021014004490000");
		else if (i == CHALMERS)
			content.put("StopAreaExternalId", "9021014001960000");
		else if (i == LINDHOLMSPIREN)
			content.put("StopAreaExternalId", "9021014004493000");
		else
			throw new Exception("Illegal BussStop");

		Request.put("request", content);

		HttpPost post = new HttpPost(
				"http://www.vasttrafik.se/CustomerServices/EPiServerWs/Service.svc/GetNextTrips");
		post.setHeader("Content-Type", "application/json; charset=UTF-8");
		post.setHeader("Accept", "text/plain");
		post.setEntity(new ByteArrayEntity(Request.toString().getBytes("UTF-8")));

		HttpResponse response = Busclient.execute(post);
		//Note: if response contains XML, then serverer error...
		if (response != null) {
			return EntityUtils.toString(response.getEntity()).replaceAll("\\s","");
		} else
			throw new Exception("NOT FOUND");

	}

	/**
	 * Get anmälda tentamenstillfällen
	 * 
	 * @return String -the page "anmälda tentamenstillfällen"
	 * @return String -error if not logged in
	 * 
	 */
	public synchronized  String getAnTenta()
			throws IllegalStateException, IOException {
		HttpGet httpget = new HttpGet(
				"https://student.portal.chalmers.se/sv/chalmersstudier/tentamen/Sidor/VisaAnmaldaTentamensTillfallen.aspx");
		HttpResponse hr = null;
		hr = client.execute(httpget, context);
		httpget.getParams().setBooleanParameter(
				CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
		String fix = inputStreamToString(hr.getEntity().getContent());
		if (fix.contains("<div class=\"bm-content\">")) {
			int start = fix.indexOf("<div class=\"bm-content\">");
			int end = fix
					//.indexOf("<span id=\"ctl00_ctl21_g_930ab088_8ce9_468b_8e5a_8b8f771de08d_ctl00_lblIntroductionText2\">"); // Vart
					.indexOf("<a id=\"ctl00_PlaceHolderMain_ctl02_ctl00_BackLink\" href=\"https://student.portal.chalmers.se/sv/chalmersstudier/tentamen\">Tentamen</a>");
			String check = fix.substring(start, end).replaceAll(
					"<table width=\"95%\">", "<table width=\"100%\">");
			return check;
		} else
			return "error!";
	}

	/**
	 * Same as getAnTenta but in english.
	 * 
	 * @return String - A string containing the html code needed to present the
	 *         information in a webview.
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	public synchronized  String getAnTentaEN()
			throws IllegalStateException, IOException {
		HttpGet httpget = new HttpGet(
				"https://student.portal.chalmers.se/en/chalmersstudies/Examinations/Pages/Examinations%20you%20are%20signed%20up%20for.aspx");
		HttpResponse hr = null;
		httpget.getParams().setBooleanParameter(
				CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
		hr = client.execute(httpget, context);

		String fix = inputStreamToString(hr.getEntity().getContent());
		if (fix.contains("<div class=\"middle\">")) {
			int start = fix.indexOf("<div class=\"middle\">");
			int end = fix
					.indexOf("<a id=\"ctl00_PlaceHolderMain_ctl02_ctl00_BackLink\" href=\"https://student.portal.chalmers.se/en/chalmersstudies/Examinations\">Examinations</a>");
			String check = fix.substring(start, end).replaceAll(
					"<table width=\"95%\">", "<table width=\"100%\">");
			;
			check = check.replaceAll("../../../../",
					"https://studentportal.chalmers.se/en/");
			return check;

		} else
			return "error!";
	}

	/**
	 * Get anmälan till tentamenstillfällen
	 * 
	 * @return String -the page "Anmälan till tentamenstillfällen"
	 * @return String -error if not logged in
	 * 
	 */

	public synchronized  String getAnmalTenta()
			throws IllegalStateException, IOException {
		HttpGet httpget = new HttpGet(
				"https://student.portal.chalmers.se/sv/chalmersstudier/tentamen/Sidor/anmal-dig-till-tentamen.aspx");
		HttpResponse hr = null;
		httpget.getParams().setBooleanParameter(
				CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
		hr = client.execute(httpget, context);

		String fix = inputStreamToString(hr.getEntity().getContent());
		if (fix.contains("<div class=\"middle\">")) {
			int start = fix.indexOf("<div class=\"middle\">");
			int end = fix
					.indexOf("<span id=\"ctl00_ctl21_g_bd6ed3fe_d59c_4a3c_97f2_ba73834899e3_ctl00_lblIntroductionText2\"></span>");
			String check = fix.substring(start, end).replaceAll(
					"<table width=\"95%\">", "<table width=\"100%\">");
			check = check.replaceAll("å", "&#229;").replaceAll("ä", "&#228;")
					.replaceAll("ö", "&#246;").replaceAll("é", "&#233;")
					.replaceAll("Å", "&#197;").replaceAll("Ä", "&#196;")
					.replaceAll("Ö", "&#214;");

			return Uri.encode(check);
		} else
			return "error!";
	}

	/**
	 * get finished courses from studentportalen.
	 * 
	 * @return String - the "avslutade kurser" page
	 * @return String - "error" if not logged in
	 */
	public synchronized  String getAvslKurs()
			throws IllegalStateException, IOException {
		HttpGet httpget = new HttpGet(
				"https://student.portal.chalmers.se/sv/chalmersstudier/minaresultatochintyg/Sidor/Avslutadekurser.aspx");
		HttpResponse hr = null;
		httpget.getParams().setBooleanParameter(
				CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
		hr = client.execute(httpget, context);
		String fix = inputStreamToString(hr.getEntity().getContent());
		if (fix.contains("<div class=\"bm-content\">")) {
			int start = fix.indexOf("<div class=\"bm-content\">");
			int end = fix
					.indexOf("<span id=\"ctl00_ctl21_g_1c80c04e_45a3_4c33_b598_59cd67741e69_ctl00_lblIntroduction2\">");
			String check = fix.substring(start, end).replaceAll(
					"<table width=\"95%\">", "<table width=\"100%\">");
			check = check.replaceAll("Högskolepoäng", "HP")
					.replaceAll("å", "&#229;").replaceAll("ä", "&#228;")
					.replaceAll("ö", "&#246;").replaceAll("é", "&#233;")
					.replaceAll("Å", "&#197;").replaceAll("Ä", "&#196;")
					.replaceAll("Ö", "&#214;");
			return Uri.encode(check);
		} else
			return "error!";
	}

	/**
	 * Same as getAvslKurs but in english.
	 * 
	 * @return String
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	public synchronized  String getAvslKursEN()
			throws IllegalStateException, IOException {
		HttpGet httpget = new HttpGet(
				"https://student.portal.chalmers.se/en/chalmersstudies/courseinformation/Pages/PassedCourses.aspx");
		HttpResponse hr = null;
		httpget.getParams().setBooleanParameter(
				CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
		hr = client.execute(httpget, context);

		String fix = inputStreamToString(hr.getEntity().getContent());
		if (fix.contains("<div class=\"middle\">")) {
			int start = fix.indexOf("<div class=\"middle\">");
			int end = fix
					.indexOf("<span id=\"ctl00_ctl21_g_5417b3bc_d8bb_47b2_97da_c409a548a9a0_ctl00_lblIntroduction2\">");
			String check = fix.substring(start, end).replaceAll(
					"<table width=\"95%\">", "<table width=\"100%\">");

			return Uri.encode(check);
		} else
			return "error!";
	}

	/**
	 * Get courses this term from studentportalen.
	 * 
	 * @return String - the "kurser denna termin" page
	 * @return String - "error" if not logged in
	 * @throws IOException
	 * @throws ClientProtocolException
	 */

	private synchronized  ArrayList<String> getCourses(String quk1) {
		ArrayList<String> list = new ArrayList<String>();
		Scanner scanner = new Scanner(quk1);
		String quk = null;
		while (scanner.hasNext())
			quk += scanner.next();
		quk.trim();
		int i = 0;
		while (true) {
			String ch = "valign=\"top\"><tdstyle=\"padding-right:10px;\">";
			i = quk.indexOf(ch) + ch.length();
			if (quk.indexOf(ch) == -1)
				break;
			int h = i + 6;
			String first = quk.substring(i, h);
			quk = quk.substring(h);
			list.add(first);
		}
		return list;
	}

	private synchronized  ArrayList<String> getCodes(
			ArrayList<String> codes) throws IllegalStateException, IOException {
		ArrayList<String> list = new ArrayList<String>();
		HttpGet httpget;
		for (String l : codes) {
			httpget = new HttpGet(
					"https://web.timeedit.se/chalmers_se/db1/timeedit/p/public/objects.html?max=15&fr=t&partajax=t&im=f&sid=3&search_text="
							+ l + "&types=182");
			HttpResponse hr = client.execute(httpget, context);
			String resp = inputStreamToString(hr.getEntity().getContent());
			resp = resp.substring(
					resp.indexOf("data-id=\"") + "data-id=\"".length(),
					resp.indexOf("\" data-name="));
			list.add(resp);
		}
		return list;
	}

	public synchronized  String getKurserSch()
			throws IllegalStateException, ClientProtocolException, IOException {
		HttpGet httpget2 = new HttpGet(
				"https://student.portal.chalmers.se/nolayout/Sidor/sv_KurserDennaTermin.aspx");

		HttpResponse hr = client.execute(httpget2, context);
		String course = inputStreamToString(hr.getEntity().getContent());
		ArrayList<String> courses = getCourses(course);
		ArrayList<String> databasCodes = getCodes(courses);
		Calendar c = Calendar.getInstance();
		int datum = c.get(Calendar.MONTH);

		String manad = "";
		switch (datum) {
		case Calendar.JANUARY: {
			manad = "01";
			break;
		}
		case Calendar.FEBRUARY: {
			manad = "02";
			break;
		}
		case Calendar.MARCH: {
			manad = "03";
			break;
		}
		case Calendar.APRIL: {
			manad = "04";
			break;
		}
		case Calendar.MAY: {
			manad = "05";
			break;
		}
		case Calendar.JUNE: {
			manad = "06";
			break;
		}
		case Calendar.JULY: {
			manad = "07";
			break;
		}
		case Calendar.AUGUST: {
			manad = "08";
			break;
		}
		case Calendar.SEPTEMBER: {
			manad = "09";
			break;
		}
		case Calendar.OCTOBER: {
			manad = "10";
			break;
		}
		case Calendar.NOVEMBER: {
			manad = "11";
			break;
		}
		case Calendar.DECEMBER: {
			manad = "12";
			break;
		}
		}

		// String date =
		// c.get(Calendar.YEAR)+""+c.get(Calendar.MONTH)+1+""+c.get(Calendar.DAY_OF_MONTH)+"";
		String date;
		if (c.get(Calendar.DAY_OF_MONTH) < 10)
			date = c.get(Calendar.YEAR) + "" + manad + "0"
					+ c.get(Calendar.DAY_OF_MONTH) + "";
		else
			date = c.get(Calendar.YEAR) + "" + manad + ""
					+ c.get(Calendar.DAY_OF_MONTH) + "";
		String toDate = null;
		int year = c.get(Calendar.YEAR);
		int month = 0;
		int day = 10;
		if (Integer.parseInt(getMonth(c.get(Calendar.MONTH))) + 6 > 12) {
			year++;
			month = Integer.parseInt(getMonth(c.get(Calendar.MONTH) - 6));

		} else
			month = Integer.parseInt(getMonth(c.get(Calendar.MONTH) + 6));
		if (month < 10)
			toDate = year + "0" + month + "" + day;
		else
			toDate = year + "" + month + "" + day;
		String getit = "https://web.timeedit.se/chalmers_se/db1/timeedit/p/public/r.html?sid=3&h=t&p="
				+ date + ".x," + toDate + ".x&objects=";
		for (int t = 0; t < databasCodes.size(); t++) {
			if (t < databasCodes.size() - 1)
				getit += databasCodes.get(t) + ",";
			else
				getit += databasCodes.get(t);
		}
		getit += "&ox=0&types=0&fe=0";
		HttpGet httpget = new HttpGet(getit);
		hr = null;
		httpget.getParams().setBooleanParameter(
				CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
		hr = client.execute(httpget, context);

		String fix = inputStreamToString(hr.getEntity().getContent());
		fix = fix
				.replaceAll("href=\"/", "href=\"https://web.timeedit.se/")
				.replaceAll("src=\"/", "src=\"https://web.timeedit.se/")
				.replaceAll("data-url=\"/",
						"data-url=\"https://web.timeedit.se/")
				.replaceAll("å", "&#229;").replaceAll("ä", "&#228;")
				.replaceAll("ö", "&#246;").replaceAll("é", "&#233;")
				.replaceAll("Å", "&#197;").replaceAll("Ä", "&#196;")
				.replaceAll("Ö", "&#214;");
		;
		return Uri.encode(fix);
	}

	private  String getMonth(int datum) {
		String manad = "";
		switch (datum) {
		case Calendar.JANUARY: {
			manad = "01";
			break;
		}
		case Calendar.FEBRUARY: {
			manad = "02";
			break;
		}
		case Calendar.MARCH: {
			manad = "03";
			break;
		}
		case Calendar.APRIL: {
			manad = "04";
			break;
		}
		case Calendar.MAY: {
			manad = "05";
			break;
		}
		case Calendar.JUNE: {
			manad = "06";
			break;
		}
		case Calendar.JULY: {
			manad = "07";
			break;
		}
		case Calendar.AUGUST: {
			manad = "08";
			break;
		}
		case Calendar.SEPTEMBER: {
			manad = "09";
			break;
		}
		case Calendar.OCTOBER: {
			manad = "10";
			break;
		}
		case Calendar.NOVEMBER: {
			manad = "11";
			break;
		}
		case Calendar.DECEMBER: {
			manad = "12";
			break;
		}
		}
		return manad;
	}

	public synchronized  String getKurser(float metrics)
			throws IllegalStateException, IOException {
		HttpGet httpget = new HttpGet(
				"https://student.portal.chalmers.se/sv/chalmersstudier/minkursinformation/Sidor/KurserDennaTermin.aspx");
		HttpResponse hr = null;
		httpget.getParams().setBooleanParameter(
				CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
		hr = client.execute(httpget, context);

		String fix = inputStreamToString(hr.getEntity().getContent());
		// test!//

		if (fix.contains("div class=\"middle\"")) {
			int start = fix.indexOf("<div class=\"middle\">");
			int end = fix
					.indexOf("<a id=\"ctl00_PlaceHolderMain_ctl02_ctl00_BackLink");
			// int end = fix
			// .indexOf("<span id=\"ctl00_ctl19_g_b1a493ac_ef5b_46db_9d96_edcbf45406b0_ctl00_lblIntroductionText2\">");
			// String check = fix.substring(start, end).replaceAll(
			// "<table width=\"95%\">", "<table width=\"100%\">");
			// check = check
			// .replaceAll("Högskolepoäng", "HP")
			// .replaceAll("/sv/",
			// "https://student.portal.chalmers.se/sv/")
			// .replaceAll("\\s+", " ")
			// .replaceAll("../../../../",
			// "https://studentportal.chalmers.se/")
			// .replaceAll("å", "&#229;").replaceAll("ä", "&#228;")
			// .replaceAll("ö", "&#246;").replaceAll("é", "&#233;")
			// .replaceAll("Å", "&#197;").replaceAll("Ä", "&#196;")
			// .replaceAll("Ö", "&#214;");

			String check = fix.substring(start, end);
			check = check
					.replaceAll("<table width=\"95%\">",
							"<table width=\"100%\">")
					// check = check.replace("<div style=\"width: 620px\">",
					// "<div style=\"width: "+(int)metrics+"px\">")
					.replaceAll("Högskolepoäng", "HP")
					.replaceAll("/nolayout/",
							"https://student.portal.chalmers.se/nolayout/")
					.replaceAll("/sv/",
							"https://student.portal.chalmers.se/sv/")
					.replaceAll("\\s+", " ")
					.replaceAll("../../", "https://studentportal.chalmers.se/")
					.replaceAll("width=\"660\"", "width=\"" + metrics + "\"")
					.replaceAll("å", "&#229;").replaceAll("ä", "&#228;")
					.replaceAll("ö", "&#246;").replaceAll("é", "&#233;")
					.replaceAll("Å", "&#197;").replaceAll("Ä", "&#196;")
					.replaceAll("Ö", "&#214;");
			return Uri.encode(check);
		} else
			return "error!";
	}

	/**
	 * Get courses this term from studentportalen.
	 * 
	 * @return String - the "kurser denna termin" page
	 * @return String - "error" if not logged in
	 */
	public synchronized  String getKurser() throws IllegalStateException,
			IOException {
		HttpGet httpget = new HttpGet(
				"https://student.portal.chalmers.se/sv/chalmersstudier/minkursinformation/Sidor/KurserDennaTermin.aspx");
		HttpResponse hr = null;
		httpget.getParams().setBooleanParameter(
				CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
		hr = client.execute(httpget, context);

		String fix = inputStreamToString(hr.getEntity().getContent());
		if (fix.contains("<div class=\"middle\">")) {
			int start = fix.indexOf("<div class=\"middle\">");
			int end = fix
					//.indexOf("<span id=\"ctl00_ctl21_g_6a617376_6226_443a_9695_a059f60ccdfc_ctl00_lblIntroductionText2\">");
					.indexOf("<a id=\"ctl00_PlaceHolderMain_ctl02_ctl00_BackLink\" href=\"https://student.portal.chalmers.se/sv/chalmersstudier/minkursinformation\">Kursinformation</a>");
					String check = fix.substring(start, end).replaceAll(
					"<table width=\"95%\">", "<table width=\"100%\">");
			check = check
					.replaceAll("Högskolepoäng", "HP")
					.replaceAll("/sv/",
							"https://student.portal.chalmers.se/sv/")
					.replaceAll("\\s+", " ")
					.replaceAll("../../../../",
							"https://studentportal.chalmers.se/")
					.replaceAll("å", "&#229;").replaceAll("ä", "&#228;")
					.replaceAll("ö", "&#246;").replaceAll("é", "&#233;")
					.replaceAll("Å", "&#197;").replaceAll("Ä", "&#196;")
					.replaceAll("Ö", "&#214;");
			return Uri.encode(check);
		} else
			return "error!";
	}

	/**
	 * Same as getKurser but in english.
	 * 
	 * @return String
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	public synchronized  String getKurserEN()
			throws IllegalStateException, IOException {
		HttpGet httpget = new HttpGet(
				"https://student.portal.chalmers.se/en/chalmersstudies/courseinformation/Pages/CoursesThisTerm.aspx");
		HttpResponse hr = null;
		httpget.getParams().setBooleanParameter(
				CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
		hr = client.execute(httpget, context);

		String fix = inputStreamToString(hr.getEntity().getContent());
		if (fix.contains("<div class=\"middle\">")) {
			int start = fix.indexOf("<div class=\"middle\">");
			int end = fix
					.indexOf("<a id=\"ctl00_PlaceHolderMain_ctl02_ctl00_BackLink\" href=\"https://student.portal.chalmers.se/en/chalmersstudies/courseinformation\">Course Information</a>");
			String check = fix.substring(start, end).replaceAll(
					"<table width=\"95%\">", "<table width=\"100%\">");
			check = check
					.replaceAll("../../../../",
							"https://student.portal.chalmers.se/sv/")
					.replaceAll("/en/",
							"https://student.portal.chalmers.se/en/")
					.replaceAll("\\s+", " ")
					.replace("<table width=\"95%\">", "<table width=\"100%\">");
			return Uri.encode(check);
		} else
			return "error!";
	}

	/**
	 * Get ExamResults from studentportalen.
	 * 
	 * @return String - a string optimized to be shown in a webview.
	 * @return String - "error" if not logged in
	 */
	public synchronized  String getresult() throws IllegalStateException,
			IOException {
		HttpGet httpget = new HttpGet(
				"https://student.portal.chalmers.se/sv/chalmersstudier/minaresultatochintyg/Sidor/Resultatforteckning.aspx");
		HttpResponse hr = null;
		httpget.getParams().setBooleanParameter(
				CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
		hr = client.execute(httpget, context);
		String fix = inputStreamToString(hr.getEntity().getContent())
				.toString();
		try {
			DOMPARSER.getResultat(fix);
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (fix.contains("background-color:Silver")) {
			int start = fix
					.indexOf("<div id=\"ctl00_ctl21_g_a5cd361f_ed2e_43af_966a_2849bc43261c_ctl00_pnlContent\">");
			int end = fix
					.indexOf("<span id=\"ctl00_ctl21_g_a5cd361f_ed2e_43af_966a_2849bc43261c_ctl00_lblIntroduction2")
					+ "<span id=\"ctl00_ctl21_g_a5cd361f_ed2e_43af_966a_2849bc43261c_ctl00_lblIntroduction2"
							.length();
			String check = fix.substring(start, end).replaceAll(
					"<table width=\"95%\">", "<table width=\"100%\">");
			String check2 = check.replaceAll("Högskolepoäng", "Hp")
					.replaceAll("Provpoäng", "P.").replaceAll("å", "&#229;")
					.replaceAll("ä", "&#228;").replaceAll("ö", "&#246;")
					.replaceAll("é", "&#233;").replaceAll("Å", "&#197;")
					.replaceAll("Ä", "&#196;").replaceAll("Ö", "&#214;");

			return "<html><head><title>Hej</title></head><body>"
					+ Uri.encode(check2) + "</div></body></html>";

		} else
			return "error!";
	}

	/**
	 * Returns a list with courses and mom for results
	 * 
	 * @return
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	public synchronized  List<Kurs> getRESULT()
			throws IllegalStateException, IOException {
		HttpGet httpget = new HttpGet(
				"https://student.portal.chalmers.se/sv/chalmersstudier/minaresultatochintyg/Sidor/Resultatforteckning.aspx");
		HttpResponse hr = null;
		httpget.getParams().setBooleanParameter(
				CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
		hr = client.execute(httpget, context);
		String fix = inputStreamToString(hr.getEntity().getContent())
				.toString();
		try {
			return DOMPARSER.getResultat(fix);
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	public synchronized  List<Kurs> getRESULTEN()
			throws IllegalStateException, IOException {
		HttpGet httpget = new HttpGet(
				"https://student.portal.chalmers.se/en/chalmersstudies/Studyresultsandcertificates/Pages/ListingOfResults.aspx");
		HttpResponse hr = null;
		httpget.getParams().setBooleanParameter(
				CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
		hr = client.execute(httpget, context);
		String fix = inputStreamToString(hr.getEntity().getContent())
				.toString();
		try {
			return DOMPARSER.getResultat(fix);
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	// returnerar antalet tecken från getresult()
	// Här blir ett fel vid inloggning		
	public synchronized  int getresNr() {
		HttpGet httpget = new HttpGet(
				"https://student.portal.chalmers.se/sv/chalmersstudier/minaresultatochintyg/Sidor/Resultatforteckning.aspx");
				
		HttpResponse hr = null;
		httpget.getParams().setBooleanParameter(
				CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
		try {
			hr = client.execute(httpget, context);
			String fix = inputStreamToString(hr.getEntity().getContent())
					.toString();

			if (fix.contains("background-color:Silver")) {
				int start = fix
						.indexOf("<span class=\"text-normal\">");
				int end = fix
						.indexOf("<a id=\"ctl00_PlaceHolderMain_ctl02_ctl00_BackLink\" href=\"https://student.portal.chalmers.se/sv/chalmersstudier/minaresultatochintyg\">Studieresultat...</a>");
						
				String check = fix.substring(start, end).replaceAll(
						"<table width=\"95%\">", "<table width=\"100%\">");
				String check2 = check.replaceAll("Högskolepoäng", "Hp")
						.replaceAll("Provpoäng", "P.")
						.replaceAll("å", "&#229;").replaceAll("ä", "&#228;")
						.replaceAll("ö", "&#246;").replaceAll("é", "&#233;")
						.replaceAll("Å", "&#197;").replaceAll("Ä", "&#196;")
						.replaceAll("Ö", "&#214;");

				String s = "<html><head><title>Hej</title></head><body>"
						+ Uri.encode(check2) + "</div></body></html>";
				int antal = s.length();

				return antal;

			}
		} catch (ClientProtocolException e) {

		} catch (IOException e) {

		}

		return -1;

	}

	/**
	 * Same as getResult but in english.
	 * 
	 * @return String
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	public synchronized  String getresultEN()
			throws IllegalStateException, IOException {
		HttpGet httpget = new HttpGet(
				"https://student.portal.chalmers.se/en/chalmersstudies/Studyresultsandcertificates/Pages/ListingOfResults.aspx");
		HttpResponse hr = null;
		httpget.getParams().setBooleanParameter(
				CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
		hr = client.execute(httpget, context);

		String fix = inputStreamToString(hr.getEntity().getContent());
		if (fix.contains("<div class=\"bm-content\">")) {
			int start = fix.indexOf("<div class=\"bm-content\">");
			int end = fix
					.indexOf("<span id=\"ctl00_ctl21_g_a8bb5025_c9de_4c4e_9520_492b357c326f_ctl00_lblIntroduction2\">");
			String check = fix
					.substring(start, end)
					.replaceAll("Testpoints", "P.")
					.replaceAll("<table width=\"95%\">",
							"<table width=\"100%\">");
			check = check.replaceAll("../../../../",
					"https://studentportal.chalmers.se/en");
			return Uri.encode(check);
		} else
			return "error!";
	}
	
	/**
	 * Returnerar en lista av tentor. 
	 * 
	 * @return
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	public synchronized  List<Tenta> getTentor()
			throws IllegalStateException, IOException {
		HttpGet httpget = new HttpGet(
				"https://student.portal.chalmers.se/sv/chalmersstudier/tentamen/Sidor/VisaAnmaldaTentamensTillfallen.aspx");
		HttpResponse hr = null;
		httpget.getParams().setBooleanParameter(
				CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
		hr = client.execute(httpget, context);
		String fix = inputStreamToString(hr.getEntity().getContent())
				.toString();
		int start = fix.indexOf("<div class=\"bm-content\">");
		int end = fix.indexOf("<a id=\"ctl00_PlaceHolderMain_ctl02_ctl00_BackLink\" href=\"https://student.portal.chalmers.se/sv/chalmersstudier/tentamen\">Tentamen</a>");
		String check = fix.substring(start, end).replaceAll(
				"<table width=\"95%\">", "<table width=\"100%\">");
		
		try {
			return DOMPARSER.getTentor(check);
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * Returnerar en lista av tentor. 
	 * 
	 * @return
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	public synchronized  List<Tenta> getTentorEN()
			throws IllegalStateException, IOException {
		HttpGet httpget = new HttpGet(
				"https://student.portal.chalmers.se/en/chalmersstudies/Examinations/Pages/Examinations%20you%20are%20signed%20up%20for.aspx");
		HttpResponse hr = null;
		httpget.getParams().setBooleanParameter(
				CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
		hr = client.execute(httpget, context);
		String fix = inputStreamToString(hr.getEntity().getContent())
				.toString();
		int start = fix.indexOf("<div class=\"bm-content\">");
		int end = fix.indexOf("<a id=\"ctl00_PlaceHolderMain_ctl02_ctl00_BackLink\" href=\"https://student.portal.chalmers.se/en/chalmersstudies/Examinations\">Examinations</a>");
		String check = fix.substring(start, end);
		
		try {
			return DOMPARSER.getTentorEN(check);
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	
	
	/**
	 * Init the httpClient for executing posts and requests
	 * 
	 */
	private synchronized  void setupClient() {

		cookieStore = new BasicCookieStore();
		client.getParams().setParameter(ClientPNames.COOKIE_POLICY,
				CookiePolicy.NETSCAPE);
		context = new BasicHttpContext();
		context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
		HttpProtocolParams
				.setUserAgent(
						client.getParams(),
						"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.186 Safari/535.1");

		HttpConnectionParams.setSoTimeout(client.getParams(), timeoutSocket);

		HttpConnectionParams.setConnectionTimeout(client.getParams(),
				timeoutConnection);

		HttpClientParams.setRedirecting(client.getParams(), true);
		hasStarted = true;

	}

	/**
	 * Transforms an inputstream to a string
	 * 
	 * @param is
	 *            - The InputStream to be converted to String.
	 * @return String - the converted Inputstream as a String.
	 */
	private synchronized  String inputStreamToString(InputStream is) {
		String line = "";
		StringBuilder total = new StringBuilder();

		// Wrap a BufferedReader around the InputStream
		BufferedReader rd = new BufferedReader(new InputStreamReader(is));

		// Read response until the end
		try {
			while ((line = rd.readLine()) != null) {
				total.append(line);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// Return full string
		return total.toString();
	}

	/**
	 * The login to studentportalen page
	 * 
	 * @param user
	 *            - username
	 * @param psw
	 *            - password
	 */
	public synchronized  void connectApache(String usr, String psw,
			boolean eng) throws Exception {
		Log.d("CALLING CONNECT APACHE", Thread.currentThread().getName());
		if ((usr.equals(userName) && psw.equals(passWord))
				&& getCookies() != null && !news.equals(""))
			throw new Exception("WRONG USRNAME");
		String res = "";
		userName = usr;
		passWord = psw;
		english = eng;

		// init a context and teh client with some things, such as redirecting
		// etc.
		// setupClient();
		// make the first get, this is for collecting the viewstate and the
		// eventvalidation, but also is a neccessary cookie set here
		HttpGet httpget = new HttpGet(
				"https://student.portal.chalmers.se/_layouts/Chalmers/Authenticate.aspx?Source=/sv/Sidor/default.aspx");
		// here is the actual request sent, the prev was a innit of a "Http:get"
		HttpResponse response = client.execute(httpget, context);
		// innit the post of cridentials and the form fields(eventvalidation ,
		// viewstate..)
		HttpPost httpPost = new HttpPost(urlLogin);
		/* test */
		httpPost.getParams().setBooleanParameter(
				CoreProtocolPNames.USE_EXPECT_CONTINUE, false);

		// set the entity (what to post), to what we gatherd from the prev, get.
		// the getViesState fixes this.
		httpPost.setEntity(new UrlEncodedFormEntity(getViesState(response),
				HTTP.UTF_8));
		// make the actual post
		response = client.execute(httpPost, context);
		// now we are at the "working..." site, just collect from the form
		// fields on that page, and post it back
		HttpPost httpPost2 = new HttpPost(urlforward);
		/* test */
		httpPost2.getParams().setBooleanParameter(
				CoreProtocolPNames.USE_EXPECT_CONTINUE, false);

		httpPost2.setEntity(new UrlEncodedFormEntity(postForward(response),
				HTTP.UTF_8));
		// set up some headers for this post, im not sure if all is needed. but
		// to be sure...
		httpPost2
				.addHeader(
						"Referer",
						"https://idp.chalmers.se/adfs/ls/?wa=wsignin1.0&wtrealm=urn:chalmers:student&wctx=https://student.portal.chalmers.se/_layouts/Chalmers/Authenticate.aspx?Source=/sv/Sidor/default.aspx");
		httpPost2.addHeader("Accept", "*/*");
		httpPost2.addHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
		httpPost2.addHeader("Accept-Language",
				"sv-SE,sv;q=0.8,en-US;q=0.6,en;q=0.4");
		httpPost2.addHeader("Cache-Control", "max-age=0");
		// make the execute

		response = client.execute(httpPost2, context);

		// read the response

		res = inputStreamToString(response.getEntity().getContent());
		if (!res.contains("Du är inloggad som"))
			throw new Exception("loginError");
		if (!eng) {
			int start = res.indexOf("<h4>Senaste nyheter</h4>");
			int end = res.indexOf("<h4>Nyheter i fokus</h4>");
			news = (String) res.subSequence(start, end);
		} else
			news = getEngNews();

		// getNewstest();
		ready = true;

	}

	/**
	 * Same as getNews but in english.
	 * 
	 * @return String - An optimized htmlString to be presented in a webview.
	 * @throws ClientProtocolException
	 * @throws IOException
	 * @throws HttpException
	 */
	private synchronized  String getEngNews()
			throws ClientProtocolException, IOException, HttpException {
		HttpGet httpget = new HttpGet(
				"https://student.portal.chalmers.se/en/pages/default.aspx");
		HttpResponse hr = null;
		httpget.getParams().setBooleanParameter(
				CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
		hr = client.execute(httpget, context);

		String fix = inputStreamToString(hr.getEntity().getContent());
		if (fix.contains("<h4>Latest news</h4>")) {
			int start = fix.indexOf("<h4>Latest news</h4>");
			int end = fix.indexOf("<h4>News in focus</h4>");

			String check = fix
					.substring(start, end)
					.replaceAll("<h4>Latest news</h4>", "")
					.replaceAll("/en/",
							"https://student.portal.chalmers.se/en/");
			return check;
		} else
			throw new HttpException();

	}

	/**
	 * Get the news from the main page.
	 * 
	 * @return String - the news from the mainpage optimized for a webview
	 *         presentation
	 * @throws Exception
	 */
	public synchronized  String getNews() throws Exception {
		if (news.equals(""))
			throw new Exception("Error");

		String f = "<html><body>"
				+ "<font color=\"white\">"
				+ (news.replaceAll("<p class=\"date\">", "</b><br>")
						.replaceAll("</p>", "<p></p>").replaceAll("aspx\">",
						"aspx\"><b>"))
						.toString()
						.replaceAll("\t", "")
						.replaceAll("href=", " style=\"color:#FFFFFF\" href=")
						.replaceAll("å", "&#229;")
						.replaceAll("ä", "&#228;")
						.replaceAll("ö", "&#246;")
						.replaceAll("é", "&#233;")
						.replaceAll("Å", "&#197;")
						.replaceAll("Ä", "&#196;")
						.replaceAll("Ö", "&#214;")

						.replaceAll("–", "-")
						.replaceAll("/sv",
								"https://student.portal.chalmers.se/sv")
						.replaceAll("<h4>Senaste nyheter</h4>", "").trim()
				+ "</font>" + "</body></html>";
		return Uri.encode(f);
	}

	public synchronized  void getNewstest() throws Exception {

		if (news.equals(""))
			throw new Exception("Error");

		String[] f = news.split("</li>");
		String[] q = new String[f.length - 1];
		for (int i = 0; i < f.length - 1; i++)
			q[i] = new String(
					Uri.encode("<html><body>"
							+ "<font size=\"2\" color=\"white\">"
							+ "<style type=\"text/css\">h1.drop-shadow { text-shadow: 2px 1px 3px black }</style><h1 class=\"drop-shadow\">"
							+ (f[i].replaceAll("<p class=\"date\">",
									"</b> <br>").replaceAll("<p>", "")
									.replaceAll("<ul class=\"list\">", "")
									.replaceAll("</p>", "").replaceAll(
									"aspx\">", "aspx\"><b>"))
									.toString()
									.replaceAll("\t", "")
									.replaceAll("href=",
											" style=\"color:#FFFFFF\" href=")
									.replaceAll("å", "&#229;")
									.replaceAll("", "")
									.replaceAll("ä", "&#228;")
									.replaceAll("ö", "&#246;")
									.replaceAll("é", "&#233;")
									.replaceAll("Å", "&#197;")
									.replaceAll("Ä", "&#196;")
									.replaceAll("Ö", "&#214;")
									.replaceAll("–", "-")
									.replaceAll("/sv",
											"https://student.portal.chalmers.se/sv")
									.replaceAll("<h4>Senaste nyheter</h4>", "")
									.replaceAll("<li>", "").trim()
							+ "</font></h1>" + "</body></html>"));
		newsString = q;
		newsReady = true;
	}

	public synchronized  String[] getNewsArray()
			throws InterruptedException {
		return newsString;
	}

	/**
	 * closes the connection
	 */
	public synchronized  void closeConnection() {

		// When HttpClient instance is no longer needed,
		// shut down the connection manager to ensure
		// immediate deallocation of all system resources
		client.getConnectionManager().shutdown();
	}

	/**
	 * Returning all the cookies needed to sync with webview.
	 * 
	 * @return List<Cookie>
	 */
	public synchronized  List<Cookie> getCookies() {
		List<Cookie> store = cookieStore.getCookies();
		return hasStarted ? cookieStore.getCookies() : null;

	}
	public synchronized void addCookies(List<Cookie> cookies){
		if(cookieStore != null)
			
		
		if(hasStarted&&cookieStore != null&&cookieStore.getCookies().size()<=2){
			for(Cookie c : cookies){
				cookieStore.addCookie(c);
				
			}
		}
	}

	/**
	 * should be named getViewState, but,.. ;) handles the form fields from the
	 * loginsite, also the usrname and psw
	 * 
	 * @param rep
	 *            - the response that is to be handled(readed from)
	 * @return a list, containg names and values(ex: VIEWSATE=dfjapfja
	 * @throws Exception
	 *             ( some exception ?)
	 */
	private synchronized  List<NameValuePair> getViesState(
			HttpResponse rep) throws Exception {
		String response = inputStreamToString(rep.getEntity().getContent());
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		Matcher v = viewstaten.matcher(response);
		Matcher e = event.matcher(response);
		if (e.find() && v.find()) {
			nvps.add(new BasicNameValuePair("__VIEWSTATE", v.group(1)));
			nvps.add(new BasicNameValuePair("__EVENTVALIDATION", e.group(1)));
			nvps.add(new BasicNameValuePair("__db", "15"));
			nvps.add(new BasicNameValuePair(
					"ctl00$ContentPlaceHolder1$UsernameTextBox", userName));
			nvps.add(new BasicNameValuePair(
					"ctl00$ContentPlaceHolder1$PasswordTextBox", passWord));

			nvps.add(new BasicNameValuePair(
					"ctl00$ContentPlaceHolder1$SubmitButton", "Logga in"));
		} else {
			throw new Exception("MatcherError");
		}

		return nvps;

	}

	/**
	 * like the getVieState method, but handles the postforward page
	 * 
	 * @param rep
	 * @return List<NameValuePair>
	 * @throws Exception
	 */
	private synchronized  List<NameValuePair> postForward(HttpResponse rep)
			throws Exception {

		String response = inputStreamToString(rep.getEntity().getContent());
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();

		Matcher w = wa.matcher(response);
		Matcher wr = wresult.matcher(response);
		Matcher wc = wctx.matcher(response);
		if (w.find() && wr.find() && wc.find()) {

			nvps.add(new BasicNameValuePair("wa", w.group(1)));
			nvps.add(new BasicNameValuePair("wresult", wr.group(1)
					.replaceAll("&lt;", "<").replaceAll("&quot;", "\"")));
			nvps.add(new BasicNameValuePair("wctx", wc.group(1)));
		} else
			throw new Exception("2 Error!");
		again = nvps;
		return nvps;

	}

}
